package net.sxjr.common;

import lombok.Getter;
import lombok.ToString;

/**
 * @author cuixc
 * @since 2018-03-20 18:25
 * <p>
 * 系统级错误码范围：1 - 1000
 * 应用级错误码范围：1001 - 9999
 **/
public interface ErrorType {

    /**
     * Standard Errors
     */
    ErrorType SUCCESS = new Default(200, "响应成功");
    ErrorType UNAUTHORIZED = new Default(401, "请求未授权");
    ErrorType NOTFIND = new Default(404, "资源未找到");
    ErrorType USERNOTFIND = new Default(405, "用户不存在");
    ErrorType passworderror = new Default(651, "用户密码错误");
    ErrorType SYSTEM_ERROR = new Default(500, "系统内部错误");
    ErrorType PARAM_REQUIRED = new Default(600, "缺少必要参数[%s]");
    ErrorType ILLEGAL_PAGE_SIZE = new Default(601, "分页参数非法");
    ErrorType LOGIN_TOKEN_EXTINCT = new Default(4001, "登入凭证失效");


    int getCode();

    String getMsg();

    @Getter
    @ToString
    class Default implements ErrorType {

        private final int code;
        private String msg;
        private Object context;

        public Default(int code, String msg) {
            this.code = code;
            this.msg = msg;
        }

        public Default(int code, String msg, Object context) {
            this.code = code;
            this.msg = msg;
            this.context = context;
        }

        public Default setContext(Object context) {
            this.context = context;
            return this;
        }

    }

    default ErrorType params(Object... params) {
        if (this instanceof Default) {
            Default type = (Default) this;
            type.msg = String.format(type.msg, params);
            return this;
        } else {
            return new Default(getCode(), String.format(getMsg(), params), null);
        }
    }

    default ErrorType context(Object context) {
        if (this instanceof Default) {
            ((Default) this).context = context;
            return this;
        } else {
            return new Default(getCode(), getMsg(), context);
        }
    }

}
